/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import controller.ClientImpl;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.WindowListener;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import model.User;

/**
 *
 * @author asmaa
 */
public class ChatWindow extends javax.swing.JFrame {

    /**
     * Creates new form ChatWindow
     */
    Map <String, URL> hm ;
    ImageIcon[] images;
    Integer[] intArray;
    int confId;
    
    User[] users;
    DefaultListModel listModel = new DefaultListModel();
    
    public ChatWindow(User user , String myUserName) {

        users = new User[1];
        users[0] = user;
          
        listModel.addElement(user.getUserName());
        emotionsSetup();
        
        initComponents();
        
        initSettings(myUserName);
        
    }
     
    public ChatWindow(User[] _users, int _confId ,  String myUserName) {
       
        confId = _confId;
                
        users=_users;
        
        for (User username : _users) {            
            listModel.addElement(username.getUserName());
        }
        
        emotionsSetup();
        
        initComponents();
        
        initSettings(myUserName);
        
        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        jTextField2.setVisible(false);
        
    }
    
    private void emotionsSetup(){
        hm = new HashMap<>(); 
              
        hm.put("(angel)",getClass().getResource("images/angle.png") );
        hm.put("(angry)",getClass().getResource("images/angry.png"));
        hm.put(":|",getClass().getResource("images/astonish.png") );
        hm.put("8-)",getClass().getResource("images/cool.png") );
        hm.put(":'(",getClass().getResource("images/cry.png"));
        hm.put("(devil)",getClass().getResource("images/devil.png") );
        hm.put(":D",getClass().getResource("images/happy.png") );
        hm.put("(nerd)",getClass().getResource("images/nerd.png"));
        hm.put(":(",getClass().getResource("images/sad.png"));
        hm.put(":X",getClass().getResource("images/secret.png"));
        hm.put("^_^",getClass().getResource("images/shy.png"));
        hm.put(":S",getClass().getResource("images/confused.png") );
        hm.put("(sick)",getClass().getResource("images/sick.png") );
        hm.put(":)",getClass().getResource("images/smile.png"));
        hm.put(";)",getClass().getResource("images/wink.png"));
        
        int i = 1;
        images = new ImageIcon[hm.size()+1];
        intArray = new Integer[hm.size()+1];
        
        intArray[0] =  new Integer(0);
        //images[0] = new ImageIcon(ClassLoader.getSystemResource("images/emotions.png"));
        images[0] = new ImageIcon(getClass().getResource("images/emotions.png"));

        
        for(Map.Entry<String, URL> entry : hm.entrySet()) {    

            intArray[i] =  new Integer(i);
            images[i++] = new ImageIcon(entry.getValue());
        }  
        
    }
    
    private void initSettings(String myUserName){
        
        getContentPane().setBackground(new Color(18,114,232));
        jPanel1.setBackground(new Color(18,114,232));
        jPanel2.setBackground(new Color(18,114,232));
        jPanel3.setBackground(new Color(18,114,232));
        jPanel10.setBackground(new Color(18,114,232));
        jPanel5.setBackground(new Color(18,114,232));
        jPanel2.setBackground(new Color(18,114,232));
        jPanel7.setBackground(new Color(18,114,232));
        jPanel8.setBackground(new Color(18,114,232));
        jPanel9.setBackground(new Color(18,114,232));
        jPanel11.setBackground(new Color(18,114,232));
        jPanel6.setBackground(new Color(18,114,232));
        jPanel14.setBackground(new Color(18,114,232));

        jList1.setModel(listModel);
        
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setTitle("Chat Window - My userName : "+ myUserName);
        
        jComboBox1.setRenderer(new ComboBoxRenderer());
        jComboBox1.setMaximumRowCount(5);
        
        jEditorPane2.setEditable(false);
        jEditorPane2.setContentType("text/html");
    
    
    }
    
    public String getFriendUserName(){
        if(users != null)
            return users[0].getUserName();
        return "";
    }
    
    public String getFriendEmail(){
        if(users != null)
            return users[0].email();
        return "";
    }
    
    public String[] getFriendsUserNames(){
        String[] _users = new String[users.length];
        for (int i = 0; i < users.length; i++) {
            _users[i] = users[i].getUserName();
        }
        return _users;
    }
    
    public String[] getFriendsEmails(){
        String[] _users = new String[users.length];
        for (int i = 0; i < users.length; i++) {
            _users[i] = users[i].email();
        }
        return _users;
    }
    
    public boolean isConference(){
        return (confId > 0)? true:false;
    }
    
    public int getConfId(){
        return confId;
    }
    
    public void addOpenSendMailListener(MouseListener sendMail){
        jLabel2.addMouseListener(sendMail);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel11 = new javax.swing.JPanel();
        jPanel15 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jEditorPane2 = new javax.swing.JEditorPane();
        jPanel9 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel7 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel12 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jPanel13 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox(intArray);
        jPanel4 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setPreferredSize(new java.awt.Dimension(400, 50));
        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel6.setPreferredSize(new java.awt.Dimension(52, 100));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/ftp_icon.png"))); // NOI18N
        jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 52, Short.MAX_VALUE)
            .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel6Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel6Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        jPanel2.add(jPanel6, java.awt.BorderLayout.WEST);

        jPanel10.setPreferredSize(new java.awt.Dimension(300, 100));
        jPanel10.setLayout(new java.awt.BorderLayout());

        jPanel14.setPreferredSize(new java.awt.Dimension(80, 50));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/blue-mail-send-icon.png"))); // NOI18N

        javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
        jPanel14.setLayout(jPanel14Layout);
        jPanel14Layout.setHorizontalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 80, Short.MAX_VALUE)
            .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel14Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        jPanel14Layout.setVerticalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 54, Short.MAX_VALUE)
            .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel14Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        jPanel10.add(jPanel14, java.awt.BorderLayout.WEST);

        jPanel2.add(jPanel10, java.awt.BorderLayout.CENTER);

        jPanel11.setPreferredSize(new java.awt.Dimension(100, 100));

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jPanel2.add(jPanel11, java.awt.BorderLayout.EAST);

        jPanel15.setOpaque(false);
        jPanel15.setPreferredSize(new java.awt.Dimension(302, 50));
        jPanel15.setLayout(new java.awt.GridLayout(1, 0));

        jTextField2.setEditable(false);
        jPanel15.add(jTextField2);

        jPanel2.add(jPanel15, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel5.setPreferredSize(new java.awt.Dimension(432, 204));
        jPanel5.setLayout(new java.awt.BorderLayout());

        jPanel8.setLayout(new java.awt.GridLayout(1, 0));

        jScrollPane2.setAutoscrolls(true);
        jScrollPane2.setViewportView(jEditorPane2);

        jPanel8.add(jScrollPane2);

        jPanel5.add(jPanel8, java.awt.BorderLayout.CENTER);

        jPanel9.setPreferredSize(new java.awt.Dimension(100, 234));
        jPanel9.setLayout(new java.awt.GridLayout(1, 0));

        jList1.setForeground(new java.awt.Color(243, 237, 36));
        jScrollPane1.setViewportView(jList1);

        jPanel9.add(jScrollPane1);

        jPanel5.add(jPanel9, java.awt.BorderLayout.EAST);

        jPanel1.add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel7.setPreferredSize(new java.awt.Dimension(432, 50));
        jPanel7.setLayout(new java.awt.BorderLayout());

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel12.setPreferredSize(new java.awt.Dimension(252, 50));
        jPanel12.setLayout(new java.awt.GridLayout(1, 0));

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });
        jPanel12.add(jTextField1);

        jPanel3.add(jPanel12, java.awt.BorderLayout.CENTER);

        jPanel13.setPreferredSize(new java.awt.Dimension(80, 0));
        jPanel13.setLayout(new java.awt.GridLayout(1, 0));

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jPanel13.add(jComboBox1);

        jPanel3.add(jPanel13, java.awt.BorderLayout.EAST);

        jPanel7.add(jPanel3, java.awt.BorderLayout.CENTER);

        jPanel4.setPreferredSize(new java.awt.Dimension(80, 50));
        jPanel4.setLayout(new java.awt.GridLayout(1, 0));

        jButton1.setText("Send");
        jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel4.add(jButton1);

        jPanel7.add(jPanel4, java.awt.BorderLayout.EAST);

        jPanel1.add(jPanel7, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        int selected = jComboBox1.getSelectedIndex();
        
        if(selected == 0) return;
        
        int i = 0;
        for(Map.Entry<String, URL> entry : hm.entrySet()) {   

            if(i == selected-1){
                jTextField1.setText(jTextField1.getText() + " " + entry.getKey() + " ");
                return;
            }
            
            i++;
        }  
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyTyped
   
    public String replaceEmotions(String msg){
        
        for(Map.Entry<String, URL> entry : hm.entrySet()) {                
            msg = msg.replaceAll(Pattern.quote(" "+entry.getKey())+"[' ']{0,1}", " <img src='"+entry.getValue().toString()+"' /> ");
        }   
        
        return msg;
    }
    
    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            //setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }


        @Override
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            //Get the selected index. (The index param isn't
            //always valid, so just use the value.)
            int selectedIndex = ((Integer)value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            //Set the icon and text.  If icon was null, say so.
            
            ImageIcon icon = images[selectedIndex];

            setIcon(icon);
            setText("");
            if (icon != null) {
                setFont(list.getFont());
            } else {
                 
                setUhOhText(" (no image available)",
                            list.getFont());
            }

            return this;
        }

        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
    
    
    public String getMsgToSend(){
        //return jTextField1.getText();
        String msg =  jTextField1.getText();
        return msg;
    }
    
    public void addSendMsgListener(ActionListener sendMsg)
    {
        jButton1.addActionListener(sendMsg);
    }
    
    public void sendMsg(String friendUserName,String msg)
    {
        int x;
        jEditorPane2.selectAll();
        x = jEditorPane2.getSelectionEnd();
        jEditorPane2.select(x,x);
        try {
            msg = replaceEmotions(msg);
            jEditorPane2.getEditorKit().read(new StringReader(friendUserName+": <br />"+msg+" <br />"), jEditorPane2.getDocument(), jEditorPane2.getDocument().getLength());
            jTextField1.setText("");
            //jScrollPane2.scrollRectToVisible(null);
        } catch (Exception ex) {
            System.out.println("Wrong Message Or Bad Location !!");
        } 
    }
    public void sendFileListener(MouseListener sendFile)
    {
        jLabel1.addMouseListener(sendFile);
    }
    
    public void addCloseWindowListener(WindowListener window){
       addWindowListener(window);
    }
    
    public void addInteractiveChatListener(CaretListener addInt)
    {
        System.out.println("Begin");
        jTextField1.addCaretListener(addInt);
    }
    
    public void setInteractiveMsgField(String d)
    {
        System.out.println("Print");
        jTextField2.setText(d);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JEditorPane jEditorPane2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
